import RPi.GPIO as GPIO
import numpy as np
import time

def init(ch_list):
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(ch_list, GPIO.OUT)
	GPIO.output(ch_list, GPIO.LOW)

def curr_zt(day_start_hr):
	tms = time.localtime(time.time())
	zt = tms.tm_hour + tms.tm_min/60.0 + tms.tm_sec/3600.0 - day_start_hr
	if zt < 0:
		zt += 24.0
	return zt

def get_zthr(clk_hr, day_start_hr):
	zthr = clk_hr - day_start_hr
	if zthr < 0 :
		zthr += 24.0
	return zthr

def switch_lights(zthr, ch_list):
	# 6 points over 24hr, 2 chanels for each point
	# ch_list[0] & [6]: light on at ZT0 ~ ZT12
	# ch_list[1] & [7]: light on at ZT4 ~ ZT16
	# ch_list[2] & [8]: light on at ZT8 ~ ZT20
	# ch_list[3] & [9]: light on at ZT12 ~ ZT0
	# ch_list[4] & [10]: light on at ZT16 ~ ZT4
	# ch_list[5] & [11]: light on at ZT20 ~ ZT8
	stat_list = []
	diff = 4
	for i in range(6):
		on_zthr = i*diff
		off_zthr = (i*diff + 12) % 24
		if on_zthr < off_zthr:
			if zthr >= on_zthr and zthr < off_zthr:
				GPIO.output(ch_list[i], GPIO.HIGH)
				GPIO.output(ch_list[i+6], GPIO.HIGH)
				stat_list.append(1)
			else:
				GPIO.output(ch_list[i], GPIO.LOW)
				GPIO.output(ch_list[i+6], GPIO.LOW)
				stat_list.append(0)
		else:
			if (zthr >= on_zthr and zthr < 24) or zthr < off_zthr:
				GPIO.output(ch_list[i], GPIO.HIGH)
				GPIO.output(ch_list[i+6], GPIO.HIGH)
				stat_list.append(1)
			else:
				GPIO.output(ch_list[i], GPIO.LOW) 
				GPIO.output(ch_list[i+6], GPIO.LOW)
				stat_list.append(0)
	return stat_list
			

def test_schedule():
	day_start_hr = 9.0
	zthr = -1
	for i in range(73):
		clk_hr = i % 24
		zthr = get_zthr(clk_hr, day_start_hr)
		print('ZT-%d: ' % int(zthr), end='')
		stat_list = switch_lights(zthr, ch_list)
		[print('%d, ' % st, end='') for st in stat_list]
		print()
		time.sleep(0.5)
	print()
	
def test_loop(ch_list, frequency):
	zt = 0
	zthr = -1
	for i in range(frequency*24):
		zt = zt + 1
		zt = 0 if zt >=24 else zt
		if zt - zthr < 0 or zt - zthr > 1:
			zthr = int(zt)
			print('current ZT-hr = %f, stat_list: ' % zt, end='')
			stat_list = switch_lights(zthr, ch_list)
			#', '.join(stat_list)
			[print('%d, ' % st, end='') for st in stat_list]
			print()
		time.sleep(0.5)

			
def start_schedule(day_start_hr=9.0):
	zt = curr_zt(day_start_hr)
	zthr = -1
	while True:
		zt = curr_zt(day_start_hr)
		if zt - zthr < 0 or zt - zthr > 1:
			zthr = int(zt)
			print('current ZT-hr = %f, stat_list: ' % zt, end='')
			stat_list = switch_lights(zthr, ch_list)
			#', '.join(stat_list)
			[print('%d, ' % st, end='') for st in stat_list]
			print()
		time.sleep(1)

if __name__=='__main__':
	ch_list = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
	frequency = 3
	init(ch_list)
	test_loop(ch_list, frequency)
	start_schedule()
	GPIO.cleanup()
